package com.ruben.simplegraphql.util;

import lombok.experimental.UtilityClass;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ConvertUtil
 *
 * @author VampireAchao
 * @since 2022/9/25
 */
@UtilityClass
public class ConvertUtil {

    private static final ConversionService CONVERSION_SERVICE = SpringContextHolder.getBean(ConversionService.class);


    public static <T> T convert(Object source, Class<T> targetType) {
        return CONVERSION_SERVICE.convert(source, targetType);
    }


    public static Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        return CONVERSION_SERVICE.convert(source, sourceType, targetType);
    }

    @SuppressWarnings("unchecked")
    public static <T, R> List<R> convertList(List<T> source, Class<R> targetClass) {
        if (CollectionUtils.isEmpty(source)) {
            return new ArrayList<>();
        }
        return (List<R>) convert(source, TypeDescriptor.collection(List.class,
                        TypeDescriptor.valueOf(source.get(0).getClass())),
                TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(targetClass)));
    }
}
